import React, {memo} from 'react';
import { connect } from 'umi';

import { Card, Breadcrumb } from 'antd';
import {  IFilter } from '@/pages/SelfQuery/type';
import { ConnectState } from '@/models/connect';

import { isLevelVisualType, getLastLevelVisualTypeVal } from '@/pages/SelfQuery/utils';

import styles from './style.less';

interface DrillPathProps {
  drillList: Array<any>;
  widget: any;
  removeDrill: (idx: number) => void;
}

const DrillPath: React.FC<DrillPathProps> = memo((props) => {
  const { drillList, widget, removeDrill } = props;
  let drillNum = 0;
  let groups = [];
  const getGroups = () => {
    let groupsArr: Array<any> = [];
    const newdrillList = drillList ? drillList : [];
    drillNum = newdrillList.length;
    if (drillNum > 0) {
      const configs: any = widget.config;
      const { drills } = configs;
      //只打印在已配置的筛选条件
      newdrillList.forEach((v: any) => {
        let aliasName = '';
        const name = v.key;
        const filters: Array<IFilter> = v.filters;
        //自定义下钻
        if (drills) {
          drills.forEach((drill: any) => {
            const { alias } = drill.field;
            if (drill.name == name && alias != '') {
              aliasName = alias;
            }
          });
        }
        const filter = filters.filter((f: IFilter) => f.name == name)[0];
        if (filter) {
          const { visualType, value } = filter;
          if (isLevelVisualType(visualType)) {
            const values = value.split('|');
            if (values.length == 1) {
              const text = getLastLevelVisualTypeVal(values[0]);
              aliasName = aliasName != '' ? `${aliasName}(${text})` : `${name}(${text})`;
            }
          }
        }
        const group = { name: name, alias: aliasName };
        groupsArr.push(group);
      });
    }
    return groupsArr;
  };

  groups = getGroups();

  return (
    <div className={styles.drillPath}>
      {drillNum != 0 && groups.length > 0 && (
        <Card size="small" title="已下钻路径：" style={{ marginTop: 40 }}>
          <Breadcrumb separator=">">
            <Breadcrumb.Item onClick={() => {removeDrill(-1)}}><b>初始化</b></Breadcrumb.Item>
            {groups.map((group: any, idx: number) => {
              const { name, alias } = group;
              const text = alias != '' ? alias : name;
              return (
                <Breadcrumb.Item
                  key={idx}
                  onClick={() => {
                    if(idx === groups.length - 1) return
                    removeDrill(idx);
                  }}
                >
                  <b className={idx === groups.length - 1 ? 'last':''}>{text}</b>
                </Breadcrumb.Item>
              );
            })}
          </Breadcrumb>
        </Card>
      )}
    </div>
  );
});

export default connect(({ widget }: ConnectState) => ({
  drillList: widget.drillList,
  widget: widget.widget,
}))(DrillPath);
